import {PlusOutlined} from '@ant-design/icons';
import {Button, Divider, message, Tag, Drawer, Input, Select, Form, Modal, Radio} from 'antd';
import {ExclamationCircleOutlined} from '@ant-design/icons';
import React, {useState, useRef, useEffect} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import EmployeeForm from './components/EmployeeForm';
import {queryStaff, updateStaff, addStaff, removeStaff, queryDepartment} from '@/services/system';

const initRecord = {
  realName:'',
  staffId:'',
  staffCode:'',
  position:'',
  tel:'',
  addr:'',
  email:'',
  staffStatus:1
}

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [departments, setDeartments] = useState([]);
  const [formTitle, setFormTitle] = useState('新增员工');
  const actionRef = useRef();
  const [formRef] = Form.useForm();
  const [row, setRow] = useState();
  const [selectedRecord, setSelectedRecord] = useState({});
  const {Option} = Select;
  const handleUpdateModalVisible = (record) => {
    formRef.setFieldsValue({
      ...record
    })
    setSelectedRecord(record)
    setFormTitle('更新员工')
    handleModalVisible(true)
  }
  const handleCreateModalVisible = () => {
    formRef.setFieldsValue({
      ...initRecord
    })
    setFormTitle('新增员工')
    handleModalVisible(true)
  }

  const getDepartment = async()=>{
    await queryDepartment({
      pageNum: 1,
      pageSize: 9999
    }).then(res=>{
      if(res && res.status === '0') {
        setDeartments(res.result.records)
      }
    })
  }

  useEffect(()=>{
    getDepartment();
  }, [])

  const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');

    try {
      await addStaff({...fields}).then(res=>{
        if (res && res.status === '0') {
          if (actionRef.current) {
            actionRef.current.reload();
          }
          hide();
          message.success('添加成功，即将刷新');
        }else {
          message.error(res.message)
        }
      })
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };

  const handleUpdate = async (fields) => {
    const hide = message.loading('正在配置');
    fields.staffId=selectedRecord.staffId
    try {
      await updateStaff({
        ...fields
      }).then(res=>{
        if (res && res.status === '0') {
          if (actionRef.current) {
            actionRef.current.reload();
          }
          hide();
          message.success('配置成功，即将刷新');
        }else {
          message.error(res.message)
        }
      })
      return true;
    } catch (error) {
      hide();
      message.error('配置失败请重试！');
      return false;
    }
  };

  const handleRemove = async (selectedRows) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      await removeStaff({
        ...selectedRows
      }).then(res=>{
        if (res && res.status === '0') {
          if (actionRef.current) {
            actionRef.current.reload();
          }
          hide();
          message.success('删除成功，即将刷新');
        }
      })
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  const deleteConfig = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `是否要删除采购编码为 【${record.purchaseCode} 】的员工？`,
      okText: '确认',
      cancelText: '取消',
    });
  };


  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '员工姓名',
      dataIndex: 'realName',
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '地址最大长度为32'
          },
          {
            required: true,
            message: '请输入{'
          },
        ],
      },
    },
    {
      title: '工号',
      dataIndex: 'staffCode',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请输入工号'
          },
        ],
      },
    },
    {
      title: '职位',
      dataIndex: 'position',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '地址最大长度为32'
          },
          {
            required: true,
            message: '请输入职位'
          },
        ],
      },
    },
    {
      title: '手机号',
      dataIndex: 'tel',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '最大长度为32'
          },
        ],
      },
    },
    {
      title: '地址',
      dataIndex: 'addr',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '地址最大长度为32'
          },
        ],
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '最大长度为32'
          },
        ],
      },
    },
    {
      title: '所属部门',
      dataIndex: 'departmentName',
      hideInSearch: true,
      hideInForm: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请选择部门'
          },
        ],
      },
    },
    {
      title: '所属部门',
      dataIndex: 'departmentId',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select>
          {
            departments.map(item=>{
              return <Option value={item.departmentId} key={item.departmentId}>{item.departmentName}</Option>
            })
          }
        </Select>
      }
    },
    {
      title: '员工状态',
      dataIndex: 'staffStatus',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请选择员工状态'
          },
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Radio.Group>
          <Radio value={1}>在职</Radio>
          <Radio value={2}>离职</Radio>
        </Radio.Group>
      },
      render: (text)=>{
        return <Tag color={text === 1? 'green': 'red'}>{text === 1? '在职': '离职'}</Tag>
      }
    },
    {
      title: '创建人',
      dataIndex: 'createByName',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => setRow(record)}>
          详情
        </a>,
        <Divider type="vertical"/>,
        <a onClick={() => handleUpdateModalVisible(record)}>修改</a>,
      ],
    },
  ];
  const detailColumns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '员工姓名',
      dataIndex: 'realName',
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '地址最大长度为32'
          },
        ],
      },
    },
    // {
    //   title: '工号',
    //   dataIndex: 'staffId',
    //   hideInForm: formTitle === '新增员工',
    //   renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
    //     return <Input disabled={type === 'form'}/>
    //   }
    // },
    {
      title: '职位',
      dataIndex: 'position',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '地址最大长度为32'
          },
        ],
      },
    },
    {
      title: '手机号',
      dataIndex: 'tel',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '最大长度为32'
          },
        ],
      },
    },
    {
      title: '地址',
      dataIndex: 'addr',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '地址最大长度为32'
          },
        ],
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '最大长度为32'
          },
        ],
      },
    },
    {
      title: '所属部门',
      dataIndex: 'departmentName',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '员工状态',
      dataIndex: 'staffStatus',
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select>
          <Option value={1}>在职</Option>
          <Option value={2}>离职</Option>
        </Select>
      },
      render: (text)=>{
        return <Tag color={text === 1? 'green': 'red'}>{text === 1? '在职': '离职'}</Tag>
      }
    },
    {
      title: '创建人',
      dataIndex: 'createByName',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true
    },
  ];
  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="staffId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleCreateModalVisible()}>
            <PlusOutlined/> 新增员工
          </Button>,
        ]}
        request={async (params, sorter, filter) => {
          const param = {...params, pageNum: params.current};
          const res = await queryStaff(param)
          return {
            data: res.result.records,
            success: true,
            total: res.result.total
          }
        }}
        columns={columns}
      />
      <EmployeeForm title={formTitle} onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable
          onSubmit={async (value) => {
            const success = formTitle === '新增员工'?await handleAdd(value): await handleUpdate(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={{
            form: formRef,
            layout: 'horizontal',
            labelAlign: 'left'
          }}
          rowKey="key"
          type="form"
          columns={columns}
        />
      </EmployeeForm>

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.realName && (
          <ProDescriptions
            column={2}
            title={row?.realName}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.realName,
            }}
            columns={detailColumns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
